package net.livingflow.web.resource;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;

import net.livingflow.Constants;
import net.livingflow.model.Flow;
import net.livingflow.util.JAXBUtils;
import net.livingflow.web.model.LivingFlow;
import net.livingflow.web.model.ObjectFactory;
import net.livingflow.web.model.XMLPack;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.view.Viewable;

/**
 * @author xueqiang.mi
 * @since 2010-11-28
 */
@Path("/flow")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class FlowResource extends BaseResource {

	@GET
	@Path("{flowId}")
	public Response getFlow(@PathParam("flowId") long flowId) {
		Flow flow = flowService.get(flowId);
		return Response.ok(new Viewable("index", flow)).build();
	}

	@GET
	@Path("{flowId}/xml")
	@Produces("application/xml")
	public String getFlowXml(@PathParam("flowId") long flowId) throws JAXBException {
		Flow flow = flowService.get(flowId);
		List<Flow> flowList = new ArrayList<Flow>();
		flowList.add(flow);
		XMLPack xPack = JAXBUtils.generateXMLPackage(flowList);
		List<XMLPack> xPacks = new ArrayList<XMLPack>();
		xPacks.add(xPack);
		LivingFlow livingFlow = JAXBUtils.generateLivingFlow(xPacks);
		JAXBElement<LivingFlow> je = new ObjectFactory().createLivingFlow(livingFlow);
		StringWriter buffer = new StringWriter();
		JAXBUtils.marshal(Constants.JAXB_CONTEXT_PATH, je, buffer);
		return buffer.toString();
	}
}
